<!--
 * @Description:
 * @Author bianpengfei
 * @create 2021/3/15 10:28
 -->
<template>
  <div :style="{ height: height + 'px', zIndex: zIndex }">
    <div
      :class="className"
      :style="{
        top: isSticky ? stickyTop + 'px' : '',
        zIndex: zIndex,
        position: position,
        width: width,
        height: height + 'px'
      }"
    >
      <slot></slot>
    </div>
  </div>
</template>

<script>
export default {
  name: 'Sticky',
  props: {
    stickyTop: {
      type: Number,
      default: 0
    },
    zIndex: {
      type: Number,
      default: 1
    },
    className: {
      type: String,
      default: ''
    },
    scrollView: {
      type: Element,
      default: null
    }
  },
  data() {
    return {
      active: false,
      position: 'relative',
      width: undefined,
      height: undefined,
      isSticky: false
    }
  },

  watch: {
    active(a, b) {
      this.$emit('onChangeActive', a)
    }
  },
  mounted () {
    this.height = this.$el.getBoundingClientRect().height
    this.throttledScrollHandler = this.$throttle(this.handleScroll, 16)
    this.debounceResizeHandler = this.$debounce(this.handleResize, 200)
    if (!this.scrollView) {
      this.$emit('update:scrollView', document.querySelector('.router-view__wrap'))
    }
    this.$nextTick(() => {
      this.scrollView.addEventListener('scroll', this.throttledScrollHandler)
      this.scrollView.addEventListener('resize', this.debounceResizeHandler)
    })
  },

  /* 踩坑*/
  activated () {
    this.reset()
  },

  beforeDestroy() {
    this.scrollView.removeEventListener('scroll', this.throttledScrollHandler)
    this.scrollView.removeEventListener('resize', this.debounceResizeHandler)
  },
  methods: {
    sticky() {
      if (this.active) {
        return
      }
      this.position = 'fixed'
      this.active = true
      this.width = this.width + 'px'
      this.isSticky = true
    },
    handleReset() {
      if (!this.active) {
        return
      }
      this.reset()
    },
    reset() {
      this.position = 'relative'
      this.width = 'auto'
      this.active = false
      this.isSticky = false
    },
    handleScroll() {
      const width = this.$el.getBoundingClientRect().width
      this.width = width || 'auto'
      const offsetTop = this.$el.getBoundingClientRect().top
      if (offsetTop < this.stickyTop) {
        this.sticky()
        return
      }
      this.handleReset()
    },
    handleResize() {
      if (this.isSticky) {
        this.width = this.$el.getBoundingClientRect().width + 'px'
      }
    }
  }
}
</script>
